package cn.oldfeel.spark.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import cn.oldfeel.spark.R;
import cn.oldfeel.spark.base.BaseFragment;
import cn.oldfeel.spark.config.UserInfo;

/**
 * 左侧菜单
 * 
 * @author oldfeel
 * 
 */
public class MainMenuFragment extends BaseFragment implements OnClickListener,
		OnCheckedChangeListener {
	/** 请求登录 */
	private static final int REQUEST_LOGIN = 9527;
	/** 邀请好友 */
	private Button btnInvite;
	/** 导航组,目前包含聊天和设置 */
	private RadioGroup rgNav;
	/** 登录按钮 */
	private Button btnLogin;
	/** 设置 */
	private SettingsFragment settingsFragment;

	public static MainMenuFragment newInstance() {
		MainMenuFragment fragment = new MainMenuFragment();
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.main_menu_view, null);
		btnInvite = (Button) view.findViewById(R.id.main_menu_invite);
		rgNav = (RadioGroup) view.findViewById(R.id.main_menu_nav);
		btnLogin = (Button) view.findViewById(R.id.main_menu_login);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		btnInvite.setOnClickListener(this);
		btnLogin.setOnClickListener(this);
		rgNav.setOnCheckedChangeListener(this);
		settingsFragment = new SettingsFragment();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_menu_login:
			login();
			break;
		case R.id.main_menu_invite:
			invite();
			break;
		default:
			break;
		}
	}

	/**
	 * 登录
	 */
	private void login() {
		Intent intent = new Intent(getActivity(), Login.class);
		startActivityForResult(intent, REQUEST_LOGIN);
	}

	/**
	 * 邀请好友
	 */
	private void invite() {
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.main_menu_chat:
			break;
		case R.id.main_menu_settings:
			showFragment(settingsFragment);
			break;
		default:
			break;
		}
	}

	/**
	 * 显示fragment
	 * 
	 * @param fragment
	 */
	private void showFragment(SettingsFragment fragment) {
		((Main) getActivity()).showFragment(fragment);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_LOGIN && resultCode == Activity.RESULT_OK) { // 登录成功
			btnLogin.setText(UserInfo.getInstance(getActivity()).getName());
			((Main) getActivity()).closeDrawers();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 设置用户名
	 * 
	 * @param instance
	 */
	public void setUserName(UserInfo userInfo) {
		btnLogin.setText(userInfo.getName());
		btnLogin.setClickable(false);
	}
}
